package com.hardroid.workload.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.hardroid.workload.R;
import com.hardroid.workload.ui.fragment.ResultBebanFragment;
import com.hardroid.workload.ui.fragment.ResultControlFragment;
import com.hardroid.workload.ui.fragment.ResultFragment;
import com.hardroid.workload.ui.fragment.ResultObsvFragment;
import com.hardroid.workload.ui.fragment.ResultQuestFragment;
import com.hardroid.workload.ui.tablet.DashboardMultiPaneActivity;
import com.hardroid.workload.utils.IResultReplacable;
import com.hardroid.workload.utils.Singleton;
import com.hardroid.workload.workcalc.Employer;
import com.hardroid.workload.workcalc.ObsvDay;
import com.hardroid.workload.workcalc.Questionaire;

/**
 * Activity untuk menangani hasil project
 * 
 * @author hartono
 * 
 */
public class ResultActivity extends Activity implements IResultReplacable {

	public enum ResultType {
		Observation, Questionaire, UnitWork
	};

	private ResultType type;
	private ResultControlFragment controlFragment;
	private ResultFragment resultFragment;
	private View eksporButton;

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_result);

		final ActionBar bar = getActionBar();
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		type = ResultType.Observation;

		controlFragment = (ResultControlFragment) getFragmentManager()
				.findFragmentById(R.id.fragment_result_control);
		resultFragment = (ResultObsvFragment) getFragmentManager()
				.findFragmentById(R.id.fragment_result);

		bar.addTab(bar
				.newTab()
				.setText("Observasi")
				.setTabListener(
						new TabListener<Fragment>(this, ResultType.Observation)));
		bar.addTab(bar
				.newTab()
				.setText("Kuesioner")
				.setTabListener(
						new TabListener<Fragment>(this, ResultType.Questionaire)));
		bar.addTab(bar
				.newTab()
				.setText("Beban Kerja")
				.setTabListener(
						new TabListener<Fragment>(this, ResultType.UnitWork)));

		if (resultFragment == null) {
			Log.i("Result Acitivy",
					"employer - replace fragment create instance" + 0);
			if (type == ResultType.Observation) {
				resultFragment = ResultObsvFragment.createInstance(0);
			}

			// Execute a transaction, replacing any existing fragment
			// with this one inside the frame.
			Log.i("Result Acitivy", "replace fragment fr begin " + 0);
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			ft.replace(R.id.fragment_result, resultFragment);
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			ft.commit();
			Log.i("Result Acitivy", "replace fragment fr end " + 0);
		}

		if (controlFragment != null) {
			((ResultControlFragment) controlFragment)
					.setEmployer(Singleton.currentProject.lEmployer);

		}
	}

	@Override
	public void replaceResultFragment(int id) {
		// TODO Auto-generated method stub
		Log.i("Result Acitivy", "replace fragment " + id);
		if (type == ResultType.Observation) {
			if (((ResultFragment) resultFragment).employerId != id) {
				Log.i("Result Acitivy",
						"employer - replace fragment create instance" + id);
				resultFragment = ResultObsvFragment.createInstance(id);

				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				Log.i("Result Acitivy", "replace fragment fr begin " + id);
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				ft.replace(R.id.fragment_result, resultFragment);
				ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				ft.commit();
				Log.i("Result Acitivy", "replace fragment fr end " + id);
			} else {
				Log.i("Result Acitivy", "no replace");
			}
		} else if (type == ResultType.Questionaire) {
			if (((ResultFragment) resultFragment).employerId != id) {
				Log.i("Result Acitivy",
						"employer - replace fragment create instance" + id);
				resultFragment = ResultQuestFragment.createInstance(id);

				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				Log.i("Result Acitivy", "replace fragment fr begin " + id);
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				ft.replace(R.id.fragment_result, resultFragment);
				ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				ft.commit();
				Log.i("Result Acitivy", "replace fragment fr end " + id);
			} else {
				Log.i("Result Acitivy", "no replace");
			}

		} else if (type == ResultType.UnitWork) {
			if (((ResultFragment) resultFragment).employerId != id) {
				Log.i("Result Acitivy",
						"employer - replace fragment create instance" + id);
				resultFragment = ResultBebanFragment.createInstance(id);

				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				Log.i("Result Acitivy", "replace fragment fr begin " + id);
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				ft.replace(R.id.fragment_result, resultFragment);
				ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				ft.commit();
				Log.i("Result Acitivy", "replace fragment fr end " + id);
			} else {
				Log.i("Result Acitivy", "no replace");
			}

		}

		// resultFragment.init();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.result_menu, menu);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		// eksporButton = (Button)
		// menu.findItem(R.id.menu_result_export).getActionView();
		// eksporButton.setOnClickListener(new View.OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		//
		// }
		// });
		return super.onCreateOptionsMenu(menu);
	}

	public StringBuffer buildDataForExport() {
		StringBuffer retval = new StringBuffer();

		retval.append("Observasi\n");
		for (Employer e : Singleton.currentProject.lEmployer){
			retval.append(e.name);
			retval.append('\t');
			retval.append(e.division);
			retval.append('\t');
			retval.append(e.unit);
			retval.append('\t');
			retval.append(e.job);
			retval.append('\t');			
			if (e.male){
				retval.append("laki-laki");				
			}else{
				retval.append("perempuan");
			}
			retval.append('\t');			
			if (e.structural){
				retval.append("struktural");				
			}else{
				retval.append("non-structural");
			}					
			retval.append('\n');
			retval.append("tanggal");
			retval.append('\t');
			retval.append("total produktif");
			retval.append('\t');
			retval.append("total non produktif");	
			retval.append('\t');				
			retval.append("persentase produktif");	
			retval.append('\n');
			for (ObsvDay d : e.sheet.lObsvDay){
				retval.append(d.obsvDate);
				retval.append('\t');
				retval.append(d.getTotalProductive());
				retval.append('\t');
				retval.append(d.getTotalNonProductive());	
				retval.append('\t');				
				retval.append(d.getPercentageProductive());	
				retval.append('\n');															
			}
			retval.append('\n');				
		}
		
		retval.append('\n');
		
		retval.append("Kuesioner\n");		
		for (Employer e : Singleton.currentProject.lEmployer){
			retval.append(e.name);
			retval.append('\t');
			retval.append(e.division);
			retval.append('\t');
			retval.append(e.unit);
			retval.append('\t');
			retval.append(e.job);
			retval.append('\t');			
			if (e.male){
				retval.append("laki-laki");				
			}else{
				retval.append("perempuan");
			}
			retval.append('\t');			
			if (e.structural){
				retval.append("struktural");				
			}else{
				retval.append("non-structural");
			}					
			retval.append('\n');
			retval.append("Kelonggaran");
			retval.append('\t');
			retval.append("P1");
			retval.append('\t');
			retval.append("P2");
			retval.append('\n');
			for (ObsvDay d : e.sheet.lObsvDay){
				retval.append(d.questionaire.getNilaiKelonggaran(e.male));
				retval.append('\t');
				retval.append(d.questionaire.getP1());
				retval.append('\t');
				retval.append(d.questionaire.getP2());
				retval.append('\n');				
			}
			retval.append('\n');				
		}
		
		retval.append('\n');				
		retval.append("Beban kerja\n");
		retval.append("nama");
		retval.append('\t');
		retval.append("divisi");
		retval.append('\t');
		retval.append("unit");
		retval.append('\t');
		retval.append("job");
		retval.append('\t');
		retval.append("gender");
		retval.append('\t');
		retval.append("jabatan");
		retval.append('\t');
		retval.append("faktor beban harian rendah");
		retval.append('\t');
		retval.append("faktor beban harian rata-rata");
		retval.append('\t');
		retval.append("faktor beban harian tinggi");
		retval.append('\t');
		retval.append("faktor beban bulanan rendah");
		retval.append('\t');
		retval.append("faktor beban bulanan rata-rata");
		retval.append('\t');
		retval.append("faktor beban bulanan tinggi");
		retval.append('\t');
		retval.append("produktif normal 1 minggu");
		retval.append('\t');
		retval.append("produktif normal 1 bulan");
		retval.append('\t');
		retval.append("produktif normal 1 tahun");
		retval.append('\t');
		retval.append("beban kerja 1 tahun");			
		retval.append('\n');
		for (Employer e : Singleton.currentProject.lEmployer){
			retval.append(e.name);
			retval.append('\t');
			retval.append(e.division);
			retval.append('\t');
			retval.append(e.unit);
			retval.append('\t');
			retval.append(e.job);
			retval.append('\t');			
			if (e.male){
				retval.append("laki-laki");				
			}else{
				retval.append("perempuan");
			}
			retval.append('\t');			
			if (e.structural){
				retval.append("struktural");				
			}else{
				retval.append("non-structural");
			}
			retval.append('\t');
			retval.append(e.bebanKerja.getFaktorBebanHarianRendah());
			retval.append('\t');
			retval.append(e.bebanKerja.getFaktorBebanHarianRata2());
			retval.append('\t');
			retval.append(e.bebanKerja.getFaktorBebanHarianTinggi());
			retval.append('\t');
			retval.append(e.bebanKerja.getFaktorBebanBulananRendah());
			retval.append('\t');
			retval.append(e.bebanKerja.getFaktorBebanBulananRata2());
			retval.append('\t');
			retval.append(e.bebanKerja.getFaktorBebanBulananTinggi());
			retval.append('\t');
			retval.append(e.bebanKerja.getProduktifNormalMinggu());
			retval.append('\t');
			retval.append(e.bebanKerja.getProduktifNormalBulan());
			retval.append('\t');
			retval.append(e.bebanKerja.getProduktifNormalTahun());
			retval.append('\t');
			retval.append(e.bebanKerja.getBebanKerja1Tahun());			
			retval.append('\n');
		}
		return retval;
	}

	public boolean export() {
		try {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				
				FileOutputStream os;
				os = new FileOutputStream(new File("/sdcard/",
						Singleton.currentProject.projectName + ".dat"));
				OutputStreamWriter out = new OutputStreamWriter(os);
				String a = buildDataForExport().toString();
				
				out.write(a);
				out.close();
				System.out.println("Successfully out write");
				return true;
			} else {
				System.out.println("Cannot write file");
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if (item.getItemId() == R.id.menu_result_export) {
			// export data beban kerja
			if (export()){
				Toast.makeText(getApplication(), "Ekspor data berhasil dilakukan ke /sdcard/", Toast.LENGTH_SHORT).show();
			}else{
				Toast.makeText(getApplication(), "Ekspor data gagal dilakukan", Toast.LENGTH_SHORT).show();
			}

		} else if (item.getItemId() == android.R.id.home) {
			Intent intent = new Intent(this, DashboardMultiPaneActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public static class TabListener<T extends Fragment> implements
			ActionBar.TabListener {
		private final Activity mActivity;
		private Fragment mFragment;
		private ResultType mType;
		private FragmentTransaction sft;

		public TabListener(Activity activity, ResultType type) {
			mActivity = activity;
			mType = type;
		}

		@Override
		public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub
			Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub
			Log.i("Result Activity", "Change tab " + mType);
			((ResultActivity) mActivity).type = mType;
			sft = mActivity.getFragmentManager().beginTransaction();
			if (mType == ResultType.Observation) {
				mFragment = ResultObsvFragment
						.createInstance(((ResultActivity) mActivity).controlFragment.currentEmployerId);
			} else if (mType == ResultType.Questionaire) {
				mFragment = ResultQuestFragment
						.createInstance(((ResultActivity) mActivity).controlFragment.currentEmployerId);

			} else {
				mFragment = ResultBebanFragment
						.createInstance(((ResultActivity) mActivity).controlFragment.currentEmployerId);
			}

			sft.replace(R.id.fragment_result, mFragment);
			sft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			sft.commit();
		}

		@Override
		public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
			// TODO Auto-generated method stub
		}
	}
}
